package com.nervenets.web.controller.handler.admin.order;

import com.alibaba.fastjson.JSONArray;
import com.nervenets.utils.JodaUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.OrderStatus;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.Order;
import com.nervenets.web.rabbitmq.FlowMessage;
import com.nervenets.web.rabbitmq.FlowType;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class OrderTailConfirmHandler extends SessionHandler<OrderTailConfirmParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(OrderTailConfirmParams params, HttpServletRequest request) throws Exception {
        try {
            JSONArray.parseArray(params.getPictures(), String.class);
        } catch (Exception e) {
            return errorMessage(MessageCode.code_444, "截图格式有误");
        }

        return (String) redisSyncLocker.idLock(params.getOrderId(), o -> {
            final Order order = userDao.findById(params.getOrderId(), Order.class);
            if (null == order) return errorMessage(MessageCode.code_404, "订单不存在");

            order.getExtra().setTailConfirmName(params.getName());
            order.getExtra().setTailConfirmImages(JSONArray.parseArray(params.getPictures(), String.class));
            order.getExtra().setTailConfirmTime(JodaUtils.getTimestamp());
            order.setStatus(OrderStatus.paid);
            userDao.saveOrUpdate(order);

            messageProducer.flow(new FlowMessage(order.getUserId(), FlowType.orderTailConfirm, getIp(request), order.getId()));

            return successMessage(order);
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
